from time import sleep
from tkinter import ttk, END, INSERT, scrolledtext, W
from tkinter import filedialog
from ModeType.Base import BaseOutput

# 文本文件式输出


class TextFileResult(BaseOutput):
    def __init__(self):
        super().__init__()
        self.filePath = ''

    def createConfig(self, root):
        self.commonConfig(root)
        box = ttk.LabelFrame(root, text='text 输出配置')
        box.pack(padx=10, pady=10)

        row = 0
        ttk.Label(box, text='文件地址').grid(row=row, column=0, sticky=W)

        def selectFile():
            self.filePath = filedialog.askopenfilename(
                title='请选择一个文件', filetypes=[('文本文档', '.txt')])
            
            self.select.delete(1.0, END)
            self.select.insert(INSERT, self.filePath)

        ttk.Button(box, text="请选择txt文件", command=selectFile).grid(
            row=row, column=1)
        
        row += 1

        ttk.Label(box, text='已选文件').grid(row=row, column=0)
        self.select = scrolledtext.ScrolledText(box, height=10)
        self.select.grid(row=row, column=1)

        return box

    def run(self):
        if self.filePath == '':
            self.tips('请选择文件')
            return

        f = open(self.filePath, "r", encoding='utf-8')
        line = f.readline()
        speed = self.get_speed()
        while line:
            if self.stop:
                break
            content = line.strip('\n')
            self.keyResultContent(content)
            line = f.readline()
            sleep(speed)
